(function($){
	if(Modernizr.audio.mp3)
	{
		$.fn.musicPlayer = function(userOptions){

			
			//Defult options
			var pluginOptions = {
				autoPlay: false,
				defaultVolume: 10,
				showPlaylist:true,
				simpleControls: false,
				hidePlaylistOnStart:false,
			};
			// if user writes options then default values will be overwritten
			var finalOptions = $.extend(pluginOptions,userOptions);
			
			//returns the funtions on each DOM element that uses it.
			return this.each(function(){

			
				var player = $("<audio ></audio>");
				$("li",this).hide();

				var position = 0;		//position in playlist
				var audioCount = 0;		//audi files in playlist
				var playing = false;
				var paused = false;
				var normalTime = true;
				var dur = 0;
				var dursec = "0"+0;
				var durmin = "0"+0;
				
				//Create the playlist from given URL's

				var playlist = [];
				$("li",this).each(function(){
						playlist.push($(this).text())
						audioCount++;
				 });

				//Create HTML elements

			    var source = document.createElement('source');
				source.type='audio/mpeg';
				source.src= playlist[position];
				player.append(source);
				
				var playerContent =$("<div class='playerContent'>");

				var title = $("<p class='title'></p>");

				title.text(parseName(playlist[position]))

			    var playlistController = $("<div class='playlistController'>")
		     	var playlistShow = $("<div class='playlistShow'>");
				var songlist = $("<ul class='songlist'>")
				for(var i=0; i<playlist.length;i++){
					var song = $("<li  class='song'>");
					
					$(song).attr("id",i);
					$(song).text((i+1)+"."+parseName(playlist[i]));
					songlist.append(song);

					song.click(function(){
						selectSong($(this).attr('id'));
					});
				}
				

				var playlistButton = $("<img class='playlistButton controlButton' src='trans.png' widht='1' height='1' />");
				playlistButton.click(function(){
					playlistShow.slideToggle();
				});


				var playButton = $("<img class='play controlButton' src='trans.png' width='1' height='1' />");
				playButton.click(function(){
					play();

				});

				var pauseButton = $("<img class='pause controlButton' src='trans.png' width='1' height='1' />");
				pauseButton.click(function(){
					if(playing)
					{
						playing = false;
						paused = true;
						playButton.toggleClass("activePlay");
						pauseButton.toggleClass("activePause");
						player.get(0).pause()
					}
				});
				
				var stopButton = $("<img class='stop controlButton' src='trans.png' width='1' height='1' />");
				stopButton.click(function(){
					if(playing)
					{
						playButton.toggleClass("activePlay");
						playing = false;
					}
					player.get(0).pause();
					player.get(0).currentTime = 0;

				});

				var prevButton = $("<img class='prev controlButton' src='trans.png' width='1' height='1' />");
				prevButton.click(function(){
					
					if(position > 0)
					{
						getDuration();
						selectSong(--position);
						getDuration();
					}
					else
					{
						selectSong(position);
						player.get(0).currentTime = 0;
					}

				});
				var nextButton = $("<img class='next controlButton' src='trans.png' width='1' height='1' />");
				nextButton.click(function(){
					if(position < audioCount-1)
					{
						getDuration();
						source.type='audio/mpeg';
						source.src= playlist[++position];
						player.append(source);
						player.get(0).play();
						title.text(parseName(playlist[position]));
						selectSong(position);
					}


				});

				//Audio position slider
				var slider = $("<div class='slider'>");
				var slideControl =$("<div class='slideControl'>");
				var sliderButton =$("<img class='sliderButton' src='SLIDER.PNG'/>");
				sliderButton.css({left: 0});
				var startOffset, holderOffset, sliderWidth, handleWidth, moving;
				sliderButton.on('mousedown',function(e){
					e.preventDefault(); 
					holderOffset = slideControl.offset().left;
			        startOffset = sliderButton.offset().left - holderOffset;
			        sliderWidth = slideControl.width();
					$(document).on('mousemove', moveHandler);
					$(document).on('mouseup', stopHandler); 
				});
				function stopHandler() {

					player.get(0).currentTime = (sliderButton.offset().left-holderOffset)/(sliderWidth/player.get(0).duration);
			        $(document).off('mousemove', moveHandler);
			        $(document).off('mouseup', stopHandler);
			        moving = false;
	    		}
				function moveHandler(e) {
					moving = true;
			        var posX = e.pageX - holderOffset;
			        posX = Math.min(Math.max(0, posX), sliderWidth);
			        sliderButton.css({
			            left: posX
	     	 	  });
			    }
				slideControl.append(sliderButton);
				slider.append(slideControl);
				
				//Volume slider
				var volumeSlider = $("<div class='volumeSlider'>");
				var volumeSlideControl =$("<div class='volumeSlideControl'>");
				var volumeSliderButton =$("<img class='volumeSliderButton' src='SLIDER.PNG'/>");

				var volumeStartOffset, volumeHolderOffset, volumeSliderWidth, volumeHandleWidth;
				$(document).ready(function(){
					volumeHolderOffset = volumeSlideControl.offset().left;
			        volumeStartOffset = volumeSliderButton.offset().left - volumeHolderOffset;
			        volumeSliderWidth = volumeSlideControl.width();

			        volumeSliderButton.css({left: ((finalOptions.defaultVolume/100)*volumeSlideControl.width())});
					player.get(0).volume=(volumeSliderButton.offset().left-volumeHolderOffset)/(volumeSliderWidth);
				});
				volumeSliderButton.on('mousedown',function(e){
					e.preventDefault();
					volumeHolderOffset = volumeSlideControl.offset().left;
			        volumeStartOffset = volumeSliderButton.offset().left - volumeHolderOffset;
			        volumeSliderWidth = volumeSlideControl.width();
					$(document).on('mousemove', volumeMoveHandler);
					$(document).on('mouseup', volumeStopHandler); 
				});
				function volumeStopHandler() {

					player.get(0).volume=(volumeSliderButton.offset().left-volumeHolderOffset)/(volumeSliderWidth);
			        $(document).off('mousemove', volumeMoveHandler);
			        $(document).off('mouseup', volumeStopHandler);
	    		}
				function volumeMoveHandler(e) {
			        var posX = e.pageX - volumeHolderOffset;
			        posX = Math.min(Math.max(0, posX), volumeSliderWidth);
			        player.get(0).volume=(volumeSliderButton.offset().left-volumeHolderOffset)/(volumeSliderWidth);
			        volumeSliderButton.css({
			            left: posX
	     	 	  });
			    }
			    volumeSlideControl.append(volumeSliderButton);
				volumeSlider.append(volumeSlideControl);


				//Audio event functions

				player.on("ended", function(e){
					if(position < audioCount)
					{
						source.type='audio/mpeg';
						source.src= playlist[++position];
						player.append(source);
						player.get(0).play();
						title.text(parseName(playlist[position]));
						selectSong(position);
						getDuration();
					}
				});

			    var timer = $("<p class='timer'>00:00</p>");
			    timer.click(function(){
					if(normalTime)
					{
						normalTime = false;
						timeDisplay();
					}
					else
					{
						normalTime = true;
						timeDisplay();
					}
				});

				player.on("timeupdate",function(e){
					timeDisplay();
						if(!moving){
						holderOffset = slideControl.offset().left;
				        startOffset = sliderButton.offset().left - holderOffset;
				        sliderWidth = slideControl.width();
						var percentage = (player.get(0).currentTime / player.get(0).duration);
						sliderButton.css({left: sliderWidth*percentage});
					}
					
				});

				//Helper functions
				function getDuration(){
					dur = Math.ceil(player.get(0).duration);
					dursec = dur % 60;
					durmin = Math.floor(dur / 60);

						if(durmin < 10){
							durmin = "0"+durmin;
						}
						if(dursec < 10){
							dursec = "0"+dursec;
						}

				}

				function play(){
					if(!playing)
					{
						playing = true;
						playButton.toggleClass("activePlay");
						if(paused)
						{	
							paused = false;
							pauseButton.toggleClass("activePause");
						}
						else
						{
							selectSong(position);
						}
						
						player.get(0).play()
						getDuration();

					}
				}

				function parseName(str){
					var whole = str.split("/");
					var ret = whole[whole.length-1].split("%20").join(" ");
					if (ret.length > 35){
						var endtag = ret.split(".")[1];
						ret = (ret.substr(0,30) + "..."+endtag);
					}
					return ret;

				}
				
				function parseTime(t){
					var sec = t % 60;
					var min = Math.floor(t / 60);

					

					if(min < 10)
					{
						min = "0"+min;
					}
					if(sec < 10)
					{
						sec = "0"+sec;
					}

						return (min+":"+sec);
				}
				function timeDisplay(){

					if(normalTime == true)
					{
						var time = Math.ceil(player.get(0).currentTime);
						$(timer).text(parseTime(time));
					}
					else
					{
						var time = Math.ceil(dur-player.get(0).currentTime);
						$(timer).text("-"+ parseTime(time));

					}
				}
				
				function selectSong(pos){
						songlist.children().removeClass("songPlaying");
						songlist.children("#"+pos).addClass("songPlaying");
						source.type='audio/mpeg';
						source.src= playlist[pos];
						player.append(source);
						title.text(parseName(playlist[pos]));
						position = pos;
				}

				if(finalOptions.autoPlay)
				{
					play();
				}

				
				//Add HTML elements
				var controls = $("<div class='controls'>");
				
				if(finalOptions.showPlaylist)
				{
					controls.append(playlistButton);
				}
				if(!finalOptions.simpleControls)
				{
					controls.append(prevButton);
				}
				controls.append(playButton);
				controls.append(pauseButton);
				
				if(!finalOptions.simpleControls)
				{
					controls.append(stopButton);
					controls.append(nextButton);
				}
				
				

			
				playlistShow.append(playlistController);

				var panel = $("<div class='main'>")
				playerContent.append(player);
				playerContent.append(title);
				playerContent.append(timer);
				playerContent.append(slider);
				playerContent.append(volumeSlider);
				playerContent.append(controls);
				panel.append(playerContent);
				if(finalOptions.showPlaylist)
				{
					panel.append(playlistShow);
				}
				


				playlistController.append(songlist);
				
				selectSong(position);


				if(finalOptions.hidePlaylistOnStart)
				{
					playlistShow.hide();
				}
				$(this).append(panel);

			});
		
		};

	}
	else
	{
		$.fn.musicPlayer = function(userOptions){
			return this.each(function(){
				$("li",this).hide();
				var main = $("<div>");
				var mess = $("<p>");
				mess.text("Your browser dosent support audio mp3, songs can be downloaded here:");
				var list = $("<ul>")
				$("li",this).each(function(){
								var listitem = $("<li class='rugl'>");
								var link = $("<a>")
								link.attr("href",$(this).text());
								link.text($(this).text());
								listitem.append(link);
								list.append(listitem);
						 });
				main.append(mess);
				main.append(list);
				$(this).append(main);
			});
		}

	}
})(jQuery);
